package com.bigbigrain.jiagou.wrapper;

import cn.hutool.core.util.EscapeUtil;
import cn.hutool.core.util.StrUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * @description: xss过滤request包装类
 * @author: B1gB1gRA1n
 * @create: 2020-4-17 13:39
 **/
public class XssHttpServletRequestWrapper  extends HttpServletRequestWrapper {
    private HttpServletRequest request;
    /**
     * Constructs a request object wrapping the given request.
     *
     * @param request The request to wrap
     * @throws IllegalArgumentException if the request is null
     */
    public XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
        this.request = request;
    }

    @Override
    public String getParameter(String name) {
        // 获取之前的参数
        String olValue = super.getParameter(name);
        System.out.print("原来参数:" + olValue);
        if (!StrUtil.isNotEmpty(olValue)) {
            // 将特殊字符转换成html展示 // 3.使用(StringEscapeUtils.escapeHtml(name)转换特殊参数
            olValue = EscapeUtil.escapeHtml4(olValue);
            System.out.println("转换后" + olValue);
        }
        return olValue;
    }

    /**
     * 默认值重写这个方法就可以。 可以参照人人或者若依去实现xss过滤
     * @param name
     * @return
     */
    @Override
    public String[] getParameterValues(String name) {

        String[] values = super.getParameterValues(name);
        if (values != null)
        {
            int length = values.length;
            String[] escapseValues = new String[length];
            for (int i = 0; i < length; i++)
            {
                // 防xss攻击和过滤前后空格
                escapseValues[i] = EscapeUtil.escapeHtml4(values[i]).trim();
            }
            return escapseValues;
        }
        return super.getParameterValues(name);
    }
}
